package com.scu.qingshi.facade.domain.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.scu.qingshi.common.enums.ResponseCodeEnum;
import com.scu.qingshi.common.response.BaseResponse;
import com.scu.qingshi.config.cummunity.CommunityFactory;
import com.scu.qingshi.domain.interview.dto.*;
import com.scu.qingshi.domain.interview.param.InterviewDetailRequest;
import com.scu.qingshi.domain.interview.response.AwaitingInterviewsResponse;
import com.scu.qingshi.domain.interview.response.CommunityInterviewDetailResponse;
import com.scu.qingshi.domain.interview.response.InterviewDetailResponse;
import com.scu.qingshi.domain.interview.service.InterviewQueryService;
import com.scu.qingshi.facade.domain.InterviewQueryFacade;
import com.scu.qingshi.infrastructure.dao.po.InterUserMap;
import com.scu.qingshi.infrastructure.dao.po.InterviewProcess;
import com.scu.qingshi.infrastructure.dao.service.InterUserMapService;
import com.scu.qingshi.infrastructure.dao.service.InterviewProcessService;
import com.scu.qingshi.infrastructure.dao.service.UserService;
import com.scu.qingshi.infrastructure.utils.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author qingshi
 */
@Api(tags = "面试查询")
@RequestMapping("/interQuery")
@RestController
public class InterviewQueryFacadeImpl implements InterviewQueryFacade {

    private final Logger logger = LogManager.getLogger(this.getClass());

    @Autowired
    InterviewProcessService interviewProcessService;

    @Autowired
    InterviewQueryService interviewQueryService;

    @Autowired
    InterUserMapService interUserMapService;

    @Autowired
    UserService userService;

    @GetMapping("/getCommunityApply")
    @ApiOperation("社团获取所有申请")
    public List<ApplyCommunityDTO> getCommunityApply(String openId){

        QueryWrapper<InterUserMap> wrapper = new QueryWrapper<>();
        wrapper.eq("open_id",openId);
        List<InterUserMap> maps = interUserMapService.getBaseMapper().selectList(wrapper);
        return maps.stream().map(map -> ApplyCommunityDTO.builder()
                .applyReason(map.getApplyReason())
                .interName(map.getInterName())
                .pass(map.getPass())
                .userOpenId(userService.getById(map.getUserId()).getOpenId())
                .userId(map.getUserId())
                .interId(map.getInterId())
                .build()).collect(Collectors.toList());
    }

    @GetMapping("/detail")
    @ApiOperation("查看面试详情")
    @Override
    public InterviewDetailResponse detail(InterviewDetailRequest req) {

        InterviewDetailResponse res = new InterviewDetailResponse();

        ProcessDTO detail = interviewQueryService.getDetail(req);

        res.setProcess(detail);
        res.setCode(ResponseCodeEnum.SUCCESS.name());
        res.setMsg("查询成功");
        res.setSuccess(true);
        return res;
    }

    @GetMapping("/candidateGetInterCount")
    @ApiOperation("获取面试的数量，用于分页器")
    @Override
    public Integer candidateGetInterCount() {
        QueryWrapper<InterviewProcess> wrapper = new QueryWrapper<>();
        // 已发布
        wrapper.eq("publish", 1)
                .ge("deadline", DateUtil.Today());
        return interviewProcessService.count(wrapper);
    }

    @ApiOperation("获取自己参加的面试列表")
    @GetMapping("/candidateGetMyInter")
    @Override
    public List<MyInterviewDTO> candidateGetMyInter(Integer userId) {
        QueryWrapper<InterUserMap> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId)
                .eq("pass",1);
        List<InterUserMap> maps = interUserMapService.getBaseMapper().selectList(wrapper);

        return maps.stream().map(interUserMap -> {
            InterviewProcess process = interviewProcessService.getById(interUserMap.getInterId());

            return MyInterviewDTO.builder()
                    .interName(process.getName())
                    .interId(process.getInterId())
                    .success(interUserMap.getSuccess())
                    .communityName(CommunityFactory.getCommunity(process.getOpenId()).getName())
                    .build();
        }).collect(Collectors.toList());
    }

    @ApiOperation("游客从大厅浏览面试细节")
    @GetMapping("/touristDetail")
    @Override
    public InterviewDetailResponse previewDetail(Integer interId) {

        InterviewDetailResponse res = new InterviewDetailResponse();

        InterviewProcess process = interviewProcessService.getById(interId);
        ProcessDTO detail = new ProcessDTO();
        detail.setInterId(interId);
        detail.setContent(process.getInterContent());
        detail.setNodeCount(process.getNodeCount());
        detail.setIsPublish(process.publishVO());
        detail.setName(process.getName());
        detail.setCommunityName(CommunityFactory.getCommunity(process.getOpenId()).getName());
        detail.setDeadline(DateUtil.format(process.getDeadline()));

        res.setProcess(detail);
        res.setCode(ResponseCodeEnum.SUCCESS.name());
        res.setMsg("查询成功");
        res.setSuccess(true);
        return res;
    }

    @ApiOperation("查看我所发出的申请")
    @GetMapping("/getMyApply")
    @Override
    public List<ApplyDTO> getMyApply(Integer userId) {

        QueryWrapper<InterUserMap> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        List<InterUserMap> maps = interUserMapService.getBaseMapper().selectList(wrapper);
        return maps.stream().map(map -> ApplyDTO.builder()
                .applyReason(map.getApplyReason())
                .pass(map.getPass())
                .interName(map.getInterName())
                .communityName(CommunityFactory.getCommunity(map.getOpenId()).getName())
                .build()).collect(Collectors.toList());
    }

    @ApiOperation("社团获取一个面试流的详情")
    @GetMapping("/communityDetail")
    @Override
    public CommunityInterviewDetailResponse communityDetail(Integer interId) {
        CommunityInterviewDetailResponse res = new CommunityInterviewDetailResponse();


        CommunityProcessDTO dto = interviewQueryService.getCommunityDetail(interId);

        res.setProcessDTO(dto);
        res.setCode(ResponseCodeEnum.SUCCESS.name());
        res.setMsg("查询成功");
        res.setSuccess(true);
        return res;
    }

    @ApiOperation("社团获取自己的所有面试")
    @GetMapping("/communityGetAll")
    @Override
    public List<CommunityInterviewDTO> communityGetAllProcess(String openId) {
        QueryWrapper<InterviewProcess> wrapper = new QueryWrapper<>();
        wrapper.eq("open_id", openId);

        List<InterviewProcess> interviewProcesses = interviewProcessService.getBaseMapper().selectList(wrapper);

        return interviewProcesses.stream().map(process -> CommunityInterviewDTO.builder()
                .interId(process.getInterId())
                .interName(process.getName())
                .nodeCount(process.getNodeCount())
                .curNodeCount(process.getCurNodeCount())
                .state(process.getState())
                .build()).collect(Collectors.toList());
    }

    @ApiOperation("应试者获取已发布面试")
    @GetMapping("/candidateGetAll")
    @Override
    public List<BriefInterviewDescriptionDTO> candidateGetAllProcess(Integer pageCount, Integer pageSize) {
        Page<InterviewProcess> page = new Page<>(pageCount, pageSize);
        QueryWrapper<InterviewProcess> wrapper = new QueryWrapper<>();
        // 已发布且未结束
        wrapper.eq("publish", 1)
               .ge("deadline", DateUtil.Today());
        Page<InterviewProcess> interviewProcessPage = interviewProcessService.page(page, wrapper);
        return interviewProcessPage.getRecords().stream().map(process -> BriefInterviewDescriptionDTO.builder()
                .deadline(DateUtil.format(process.getDeadline()))
                .interContent(process.getInterContent())
                .interId(process.getInterId())
                .communityName(CommunityFactory.getCommunity(process.getOpenId()).getName())
                .nodeCount(process.getNodeCount())
                .name(process.getName())
                .openId(process.getOpenId())
                .build()).collect(Collectors.toList());
    }

    @GetMapping("/getAwaitingInterview")
    @ApiOperation("社团获取待审核的面试")
    @Override
    public BaseResponse getAwaitingInterview(Integer interId){
        AwaitingInterviewsResponse res =  interviewQueryService.getAwaitingInterview(interId);

        res.setCode(ResponseCodeEnum.SUCCESS.name());
        res.setMsg("查询成功");
        res.setSuccess(true);
        return res;
    }

}
